package com.atguigu.service.impl;

import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.PermissionDao;
import com.atguigu.dao.RolePermissionDao;
import com.atguigu.entity.Permission;
import com.atguigu.entity.RolePermission;
import com.atguigu.service.PermissionService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
@Transactional
public class PermissionServiceImpl extends BaseServiceImpl<Permission> implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Override
    protected BaseDao<Permission> getEntityDao() {
        return permissionDao;
    }

    @Override
    public List<Map<String, Object>> findPermissionByRoleId(Long roleId) {
        //查询全部权限List<Permission>
        List<Permission>permissionList=permissionDao.findAll();
        //查询当前角色所有的权限id List<Long>
        List<Long>permissionIdList=rolePermissionDao.findPermissionIdListByRoleId(roleId);
        List<Map<String,Object>>zNodes=new ArrayList<>();
        for (Permission permission : permissionList) {
                Map<String,Object>node=new HashMap<>();
                    node.put("id",permission.getId());
                    node.put("pId",permission.getParentId());
                    node.put("name",permission.getName());
                    if(permissionIdList.contains(permission.getId())) {
                        node.put("checked", true);
                    }
                    zNodes.add(node);

        }
        return zNodes;
    }

    @Override
    public void saveRolePermissionRealtionShip(Long roleId, Long[] permissionIds) {
        //删除Role的所有权限
        rolePermissionDao.deleteByRoleId(roleId);
        //重新增加role的所有权限
        if(null != permissionIds && permissionIds.length>0){
            for (Long permissionId : permissionIds) {
                if (StringUtils.isEmpty(permissionId)) {
                    continue;
                }
                RolePermission rolePermission=new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermissionDao.insert(rolePermission);
            }
        }

    }
}
